<template>
  <div>
    <!-- 面包宵导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        title="注意: 只允许为第三级分类设置相关参数!"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 商品分类选择区 -->
      <el-row class="cate_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab标签区 -->
      <el-tabs v-model="activeTabName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 stripe是带斑马纹-->
          <el-table
            border
            stripe
            :data="manyList"
            style="width: 100%"
            height="750"
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 标签列表 -->
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals"
                  :key="tag.attr_id"
                  closable
                  type="primary"
                  @close="tabClosed(scope.row, index)"
                >
                  {{ tag }}
                </el-tag>
                <!-- 动态新增标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作" width="300">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 stripe是带斑马纹-->
          <el-table
            border
            stripe
            :data="onlyList"
            style="width: 100%"
            height="750"
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 标签列表 -->
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals"
                  :key="tag.attr_id"
                  closable
                  type="primary"
                  @close="tabClosed(scope.row, index)"
                >
                  {{ tag }}
                </el-tag>
                <!-- 动态新增属性标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作" width="300">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 新增参数对话框 -->
    <el-dialog
      :title="'新增' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加参数的对话框 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 修改参数的对话框 -->
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 商品分类列表数据
      cateList: [],
      // 分类选择器选中的值的数据
      selectedKeys: [],
      // 级联选择器的配置参数
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      activeTabName: 'many', // 当前激活的tab
      manyList: [], // 动态参数列表
      onlyList: [], // 静态属性列表
      inputVisible: false, // 标签输入框是否显示标识
      inputValue: '', // 标签输入内容
      addDialogVisible: false, // 添加属性对话框是否显示
      addForm: {}, // 添加参数
      // 添加参数规则校验
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editDialogVisible: false, // 是否显示修改对话框
      editForm: {} // 修改参数
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品大的分类
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.cateList = res.data
      // console.log(res.data)
    },
    // 级联选择器的选择值
    async handleChange() {
      this.getParamsData()
    },
    // 标签点击事件
    handleTabClick() {
      console.log(this.activeTabName)
      this.getParamsData()
    },
    // 获取参数数据
    async getParamsData() {
      // 如果数组长度小于3，说明选中的不是三级分类，所以直接清空
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateIdCom}/attributes`,
        {
          params: { sel: this.activeTabName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败！')
      }
      // 把res中的attr_vals从字符串改变成数组形式，方便循环
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals.split(' ')
      })

      if (this.activeTabName === 'many') {
        this.manyList = res.data
      } else {
        this.onlyList = res.data
      }
      console.log(this.manyList)
    },
    // 关闭标签按钮
    tabClosed(row, index) {
      row.attr_vals.splice(index, 1) // 从位置index处删除一个数组项，返回值又保存回了row.attr_vals中
      this.saveAttr(row)
    },
    // 标签输入框事件
    handleInputConfirm(row) {
      // console.log(this.inputValue.trim().length)
      if (this.inputValue.trim().length > 0) {
        row.attr_vals.push(this.inputValue) // 把输入框的内容PUSH到数组中
        this.saveAttr(row)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 将属性标签保存到数据库中
    async saveAttr(row) {
      // 将修改的结果保存到数据库中
      const { data: res } = await this.$http.put(
        `categories/${this.cateIdCom}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeTabName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改属性失败！')
      }
      this.$message.success('修改成功')
    },
    // 标签的新增按钮点击事件
    showInput() {
      this.inputVisible = true
      // $nextTick表示页面重新渲染时操作。
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加参数对话框确定按钮
    async addParams() {
      const { data: res } = await this.$http.post(
        `categories/${this.cateIdCom}/attributes`,
        {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeTabName
        }
      )
      // console.log(res)
      if (res.meta.status !== 201) {
        return this.$message.error('添加参数失败！')
      }
      this.$message.success('添加参数成功！')
      this.getParamsData()
      this.addDialogVisible = false
    },
    // 关闭添加参数对话框// 监听添加对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 修改参数
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateIdCom}/attributes/${id}`,
        {
          params: { attr_sel: this.activeTabName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败！')
      }
      console.log(res)
      // this.editForm.attr_name = res.data.attr_name
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改对话框关闭
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改确定按钮
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const {
          data: res
        } = await this.$http.put(
          `categories/${this.cateIdCom}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeTabName }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败！')
        }

        this.$message.success('修改参数成功！')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 根据id删除属性
    async deleteParams(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 用户取消了删除的操作
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }

      // 删除的业务逻辑
      const { data: res } = await this.$http.delete(
        `categories/${this.cateIdCom}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败！')
      }

      this.$message.success('删除参数成功！')
      this.getParamsData()
    }
  },
  computed: {
    // 添加按钮是否禁用，如果级联选择的不是三级则禁用，是则启用
    isBtnDisabled() {
      if (this.selectedKeys.length === 3) {
        return false
      }
      return true
    },
    // 计算分类的最后一级
    cateIdCom() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      } else {
        return null
      }
    },
    // 计算标题内容
    titleText() {
      if (this.activeTabName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.cate_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 5px 10px;
}
.input-new-tag {
  width: 120px;
}
</style>